package com.example.aidl_client

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.aidl.IMyAidlInterface
import com.example.aidl.MyCallBack
import com.example.aidl.ResultHolder
//这是客户端，客户端需要和服务端的aidl文件保持一致，否则接收不到消息
class MainActivity : AppCompatActivity() {

    private var  iMyAidlInterface: IMyAidlInterface? = null
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            Log.d("TAG", "onServiceConnected:链接成功 ")
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(p1)
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
            Log.d("TAG", "onServiceDisconnected:链接失败 ")
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        //绑定服务
        val intent = Intent()
        intent.setPackage("com.example.aidl")
        intent.setAction("com.example.myService")
        bindService(intent,connection, BIND_AUTO_CREATE)

    }
    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
    }

    /**
     * 不耗时
     */
    fun add(view: View) {
        val result = ResultHolder()
        iMyAidlInterface?.add(3,4,result)
        Log.d("TAG", "add: ${result.value}")
    }

    /**
     * 耗时
     */
    fun add2(view: View) {
        iMyAidlInterface?.add2(3,4,object : MyCallBack.Stub(){
            override fun result(value: Int) {
                Log.d("TAG", "add: $value")
            }
        })

    }
}